<template>
  <div class="sport-items-container">
    <el-card class="box-card" shadow="never">
      <template #header>
        <div class="card-header">
          <div class="header-left">
            <h2 class="card-title">体测项目管理</h2>
          </div>
          <div class="header-actions">
            <div class="search-box">
              <el-input v-model="searchQuery" placeholder="搜索项目名称" clearable @clear="handleSearch" class="search-input">
                <template #prefix>
                  <el-icon>
                    <Search />
                  </el-icon>
                </template>
              </el-input>
              <el-select v-model="genderFilter" placeholder="性别筛选" clearable @change="handleSearch" class="gender-filter">
                <el-option label="全部" value="" />
                <el-option label="男" value="男" />
                <el-option label="女" value="女" />
                <el-option label="通用" value="通用" />
              </el-select>
              <el-button type="primary" @click="handleSearch" :icon="Search">搜索</el-button>
            </div>
            <el-button type="success" @click="handleAdd" :icon="Plus">添加项目</el-button>
          </div>
        </div>
      </template>

      <div class="table-container" v-loading="loading" element-loading-text="加载中..." element-loading-background="rgba(255, 255, 255, 0.8)">
        <el-table :data="paginatedSportItems" border style="width: 100%" row-key="id" highlight-current-row class="sport-items-table" :header-cell-style="{ background: '#f5f7fa', color: '#606266', fontWeight: 'bold' }" empty-text="暂无数据">
          <el-table-column prop="itemName" label="项目名称" min-width="180" align="center">
            <template #default="{ row }">
              <div class="item-name-cell">{{ row.itemName }}</div>
            </template>
          </el-table-column>

          <el-table-column prop="genderScope" label="适用性别" width="120" align="center">
            <template #default="{ row }">
              <el-tag :type="getGenderTagType(row.genderScope)" effect="light">{{ row.genderScope }}</el-tag>
            </template>
          </el-table-column>

          <el-table-column prop="unit" label="计量单位" width="120" align="center" />

          <el-table-column label="达标标准" min-width="200" align="center">
            <template #default="{ row }">
              <div class="standard-info">
                <!-- 通用项目的达标标准显示在一行 -->
                <div v-if="row.genderScope === '通用'" class="standard-item standard-unified">
                  <span class="standard-label">男:</span>
                  <span class="standard-value">{{ formatStandardValue(row.malePass, row.unit, row.itemName) }}</span>
                  <span class="standard-separator">|</span>
                  <span class="standard-label">女:</span>
                  <span class="standard-value">{{ formatStandardValue(row.femalePass, row.unit, row.itemName) }}</span>
                </div>
                <!-- 男/女性别特定项目的达标标准 -->
                <div v-else>
                  <div v-if="row.genderScope !== '女'" class="standard-item">
                    <span class="standard-label">男生:</span>
                    <span class="standard-value">{{ formatStandardValue(row.malePass, row.unit, row.itemName) }}</span>
                  </div>
                  <div v-if="row.genderScope !== '男'" class="standard-item">
                    <span class="standard-label">女生:</span>
                    <span class="standard-value">{{ formatStandardValue(row.femalePass, row.unit, row.itemName) }}</span>
                  </div>
                </div>
              </div>
            </template>
          </el-table-column>

          <el-table-column label="操作" width="180" align="center" fixed="right">
            <template #default="{ row }">
              <div class="action-buttons">
                <el-tooltip content="项目详情" placement="top" :show-after="300">
                  <el-button type="primary" size="small" @click.stop="handleView(row)" :icon="View" circle />
                </el-tooltip>
                <el-tooltip content="删除项目" placement="top" :show-after="300">
                  <el-button type="danger" size="small" @click.stop="handleDelete(row)" :icon="Delete" circle />
                </el-tooltip>
              </div>
            </template>
          </el-table-column>
        </el-table>

        <div class="pagination-container">
          <el-pagination v-model:current-page="currentPage" :page-size="pageSize" layout="total, prev, pager, next, jumper" :total="filteredSportItems.length" @current-change="handleCurrentChange" />
        </div>
      </div>
    </el-card>

    <!-- 详情/编辑对话框 -->
    <el-dialog v-model="dialogVisible" :title="dialogTitle" width="500px" :close-on-click-modal="false" :show-close="true" custom-class="sport-item-dialog">
      <div v-if="!isEditing" class="item-detail-container">
        <div class="item-title">
          <h2>{{ currentSportItem.itemName }}</h2>
          <el-tag :type="getGenderTagType(currentSportItem.genderScope)" effect="plain">{{ currentSportItem.genderScope }}</el-tag>
        </div>

        <div class="item-basic-info">
          <div class="info-label">计量单位</div>
          <div class="info-value">{{ currentSportItem.unit || '无' }}</div>
        </div>

        <div class="standards-container">
          <div class="standards-title">达标标准</div>
          <div class="standards-content">
            <div v-if="currentSportItem.genderScope !== '女'" class="standard-card male-standard">
              <div class="standard-card-title">男生标准</div>
              <div class="standard-card-value">
                {{ formatStandardValue(currentSportItem.malePass, currentSportItem.unit, currentSportItem.itemName) }}
              </div>
            </div>

            <div v-if="currentSportItem.genderScope !== '男'" class="standard-card female-standard">
              <div class="standard-card-title">女生标准</div>
              <div class="standard-card-value">
                {{ formatStandardValue(currentSportItem.femalePass, currentSportItem.unit, currentSportItem.itemName) }}
              </div>
            </div>
          </div>
        </div>

        <div class="detail-actions">
          <el-button @click="dialogVisible = false">关闭</el-button>
          <el-button type="primary" @click="handleEdit(currentSportItem)">编辑</el-button>
        </div>
      </div>

      <!-- 编辑表单部分 -->
      <div v-else class="edit-form-container">
        <el-form ref="sportItemFormRef" :model="sportItemForm" :rules="formRules" label-width="100px" label-position="right" status-icon>
          <el-form-item label="项目名称" prop="itemName">
            <el-input v-model="sportItemForm.itemName" placeholder="请输入体测项目名称" />
          </el-form-item>

          <el-form-item label="性别范围" prop="genderScope">
            <el-select v-model="sportItemForm.genderScope" placeholder="请选择适用性别" style="width: 100%">
              <el-option label="男" value="男" />
              <el-option label="女" value="女" />
              <el-option label="通用" value="通用" />
            </el-select>
          </el-form-item>

          <el-form-item label="计量单位" prop="unit">
            <el-input v-model="sportItemForm.unit" placeholder="请输入计量单位" />
          </el-form-item>

          <el-form-item v-if="sportItemForm.genderScope !== '女'" label="男生标准" prop="malePass">
            <el-input-number v-model="sportItemForm.malePass" :precision="1" :step="0.5" :min="0" style="width: 100%" />
          </el-form-item>

          <el-form-item v-if="sportItemForm.genderScope !== '男'" label="女生标准" prop="femalePass">
            <el-input-number v-model="sportItemForm.femalePass" :precision="1" :step="0.5" :min="0" style="width: 100%" />
          </el-form-item>
        </el-form>

        <div class="form-actions">
          <el-button @click="cancelEdit">取消</el-button>
          <el-button type="primary" @click="submitForm" :loading="submitting">保存</el-button>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, watch, nextTick } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Delete, View, Search } from '@element-plus/icons-vue'
import { getSportItems, deleteSportItem, addSportItem, updateSportItem } from '@/api/sportItem'

// 数据状态
const loading = ref(false)
const sportItems = ref([])
const searchQuery = ref('')
const genderFilter = ref('')
const currentPage = ref(1)
const pageSize = ref(10)
const submitting = ref(false)

// 当前项目数据和表单
const currentSportItem = ref({})
const sportItemForm = ref({
  id: null,
  itemName: '',
  genderScope: '通用',
  unit: '',
  malePass: null,
  femalePass: null
})

// 对话框状态
const dialogVisible = ref(false)
const isEditing = ref(false)
const dialogTitle = computed(() => isEditing.value ? '编辑体测项目' : '体测项目详情')
const sportItemFormRef = ref(null)

// 表单验证规则
const formRules = {
  itemName: [{ required: true, message: '请输入项目名称', trigger: 'blur' }],
  genderScope: [{ required: true, message: '请选择适用性别', trigger: 'change' }],
  unit: [{ required: false, message: '请输入计量单位', trigger: 'blur' }],
  malePass: [{ required: false, message: '请输入男生达标标准', trigger: 'blur' }],
  femalePass: [{ required: false, message: '请输入女生达标标准', trigger: 'blur' }]
}

// 过滤后的项目列表
const filteredSportItems = computed(() => {
  let result = [...sportItems.value]

  // 性别过滤
  if (genderFilter.value) {
    result = result.filter(item =>
      item.genderScope === genderFilter.value ||
      (genderFilter.value === '通用' && item.genderScope === '通用')
    )
  }

  // 关键词搜索
  if (searchQuery.value) {
    const keyword = searchQuery.value.toLowerCase()
    result = result.filter(item =>
      item.itemName.toLowerCase().includes(keyword)
    )
  }

  // 按性别范围排序：通用、男、女
  result.sort((a, b) => {
    const genderOrder = { '通用': 1, '男': 2, '女': 3 }
    return genderOrder[a.genderScope] - genderOrder[b.genderScope]
  })

  return result
})

// 分页后的项目列表
const paginatedSportItems = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value
  return filteredSportItems.value.slice(start, end)
})

// 获取性别标签类型
const getGenderTagType = (gender) => {
  const genderTypeMap = {
    '男': 'primary',
    '女': 'danger',
    '通用': 'success'
  }
  return genderTypeMap[gender] || 'info'
}

// 格式化标准值展示（特别是时间单位）
const formatStandardValue = (value, unit, itemName) => {
  if (value === null || value === undefined) return '无'

  // 处理时间类数据（秒转为分:秒格式）
  if (unit === '秒' && value >= 60) {
    const minutes = Math.floor(value / 60)
    const seconds = Math.floor(value % 60)
    return `${minutes}分${seconds.toString().padStart(2, '0')}秒`
  }

  // 处理其他特殊格式
  if (unit === '') {
    if (itemName.includes('BMI')) {
      return `≤ ${value}`
    }
    if (itemName.includes('视力')) {
      return value.toFixed(1)
    }
  }

  // 默认返回值+单位
  return `${value} ${unit}`
}

// 加载体测项目数据
const fetchSportItems = async () => {
  loading.value = true
  try {
    const res = await getSportItems()
    if (res.code === 200) {
      sportItems.value = res.data || []
    } else {
      ElMessage.error(res.message || '获取数据失败')
      sportItems.value = []
    }
  } catch (error) {
    ElMessage.error('获取体测项目数据失败')
    sportItems.value = []
  } finally {
    loading.value = false
  }
}

// 查看项目详情
const handleView = (row) => {
  currentSportItem.value = { ...row }
  isEditing.value = false
  dialogVisible.value = true
}

// 添加新项目
const handleAdd = () => {
  currentSportItem.value = {
    id: null,
    itemName: '',
    genderScope: '通用',
    unit: '',
    malePass: null,
    femalePass: null
  }
  sportItemForm.value = { ...currentSportItem.value }
  isEditing.value = true
  dialogVisible.value = true

  // 确保表单重置
  nextTick(() => {
    sportItemFormRef.value?.clearValidate()
  })
}

// 编辑项目
const handleEdit = (row) => {
  currentSportItem.value = { ...row }
  sportItemForm.value = { ...row }
  isEditing.value = true
  dialogVisible.value = true
  nextTick(() => {
    sportItemFormRef.value?.clearValidate()
  })
}

// 取消编辑
const cancelEdit = () => {
  if (currentSportItem.value.id) {
    // 如果是编辑现有项目，回到详情视图
    isEditing.value = false
  } else {
    // 如果是添加新项目，关闭对话框
    dialogVisible.value = false
  }
}

// 删除项目
const handleDelete = (row) => {
  ElMessageBox.confirm(
    `确定要删除体测项目"${row.itemName}"吗？此操作将同时删除与该项目关联的所有学生成绩记录！`,
    '删除确认',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
      customClass: 'delete-confirm-dialog',
      distinguishCancelAndClose: true,
      dangerouslyUseHTMLString: true,
      message: `<div class="delete-confirm-content">
        <i class="el-icon-warning" style="color: #E6A23C; font-size: 24px; margin-right: 10px;"></i>
        <div>
          <p><strong>您即将删除体测项目：</strong> ${row.itemName}</p>
          <p style="color: #F56C6C; margin-top: 10px;"><strong>警告：</strong>此操作将同时删除与该项目关联的所有学生成绩记录！</p>
          <p style="margin-top: 10px;">该操作不可恢复，请确认您要继续吗？</p>
        </div>
      </div>`
    }
  ).then(async () => {
    try {
      const res = await deleteSportItem(row.id)
      if (res.code === 200) {
        ElMessage.success('删除成功')
        await fetchSportItems()
      } else {
        ElMessage.error(res.message || '删除失败')
      }
    } catch (error) {
      ElMessage.error('删除失败，请重试')
    }
  }).catch(() => { })
}

// 提交表单
const submitForm = async () => {
  if (!sportItemFormRef.value) return

  await sportItemFormRef.value.validate(async (valid) => {
    if (valid) {
      submitting.value = true
      try {
        const formData = { ...sportItemForm.value }

        // 根据性别范围处理标准值
        if (formData.genderScope === '男') {
          formData.femalePass = null
        } else if (formData.genderScope === '女') {
          formData.malePass = null
        }

        let res
        if (formData.id) {
          // 更新现有项目
          res = await updateSportItem(formData.id, formData)
        } else {
          // 添加新项目
          res = await addSportItem(formData)
        }

        if (res.code === 200) {
          ElMessage.success(formData.id ? '更新成功' : '添加成功')
          dialogVisible.value = false
          await fetchSportItems() // 刷新数据
        } else {
          ElMessage.error(res.message || '操作失败')
        }
      } catch (error) {
        ElMessage.error('操作失败，请重试')
      } finally {
        submitting.value = false
      }
    }
  })
}

// 处理搜索
const handleSearch = () => {
  currentPage.value = 1
}

// 处理分页变化
const handleCurrentChange = (val) => {
  currentPage.value = val
}

// 监听筛选器变化
watch([searchQuery, genderFilter], () => {
  currentPage.value = 1
})

// 初始化
onMounted(() => {
  fetchSportItems()
})
</script>

<style lang="scss" scoped>
.sport-items-container {
  padding: 16px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  flex-wrap: wrap;
  gap: 16px;
}

.card-title {
  margin: 0;
  font-size: 18px;
  color: #303133;
}

.header-actions {
  display: flex;
  gap: 16px;
  align-items: center;
}

.search-box {
  display: flex;
  gap: 12px;
  align-items: center;
}

.search-input {
  width: 240px;
}

.gender-filter {
  width: 120px;
}

.table-container {
  margin-top: 20px;
}

.sport-items-table {
  margin-bottom: 20px;
}

.item-name-cell {
  font-weight: 500;
}

.standard-info {
  padding: 4px 8px;
}

.standard-item {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
}

.standard-unified {
  justify-content: center;
  gap: 4px;
}

.standard-separator {
  margin: 0 4px;
  color: #909399;
}

.standard-label {
  font-weight: bold;
  color: #606266;
}

.standard-value {
  color: #303133;
}

.action-buttons {
  display: flex;
  justify-content: center;
  gap: 8px;
}

.pagination-container {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
}

/* 详情对话框样式 */
:deep(.sport-item-dialog .el-dialog__body) {
  padding: 20px;
}

.item-detail-container {
  display: flex;
  flex-direction: column;
  gap: 24px;
}

.item-title {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 12px;
  margin-bottom: 10px;

  h2 {
    margin: 0;
    font-size: 24px;
    color: #303133;
  }
}

.item-basic-info {
  display: flex;
  align-items: center;
  background-color: #f5f7fa;
  padding: 12px 20px;
  border-radius: 6px;

  .info-label {
    font-weight: bold;
    color: #606266;
    width: 100px;
  }

  .info-value {
    flex: 1;
    color: #303133;
  }
}

.standards-container {
  display: flex;
  flex-direction: column;
  gap: 12px;

  .standards-title {
    font-weight: bold;
    font-size: 16px;
    color: #303133;
    margin-bottom: 8px;
  }

  .standards-content {
    display: flex;
    gap: 20px;

    .standard-card {
      flex: 1;
      display: flex;
      flex-direction: column;
      padding: 16px;
      border-radius: 8px;

      .standard-card-title {
        font-size: 14px;
        margin-bottom: 8px;
        font-weight: bold;
      }

      .standard-card-value {
        font-size: 20px;
        font-weight: 500;
      }
    }

    .male-standard {
      background-color: rgba(64, 158, 255, 0.1);
      border-left: 4px solid #409EFF;

      .standard-card-title {
        color: #409EFF;
      }
    }

    .female-standard {
      background-color: rgba(245, 108, 108, 0.1);
      border-left: 4px solid #F56C6C;

      .standard-card-title {
        color: #F56C6C;
      }
    }
  }
}

.detail-actions {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
  margin-top: 10px;
}

.edit-form-container {
  padding: 10px;
}

.form-actions {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
  margin-top: 20px;
}

/* 响应式适配 */
@media (max-width: 768px) {
  .card-header {
    flex-direction: column;
    align-items: flex-start;
  }

  .header-actions {
    flex-direction: column;
    width: 100%;
  }

  .search-box {
    flex-direction: column;
    width: 100%;
    gap: 8px;
  }

  .search-input,
  .gender-filter {
    width: 100%;
  }

  .standards-content {
    flex-direction: column;
  }
}

// 自定义删除确认对话框样式
:deep(.delete-confirm-dialog) {
  .el-message-box__header {
    background-color: #fef6e6;
    padding: 15px 20px;

    .el-message-box__title {
      color: #e6a23c;
      font-weight: bold;
    }
  }

  .el-message-box__message {
    padding-top: 15px;
  }

  .delete-confirm-content {
    display: flex;
    align-items: flex-start;

    p {
      margin: 5px 0;
      line-height: 1.5;
    }
  }

  .el-message-box__btns {
    padding: 15px 20px;

    .el-button--primary {
      background-color: #f56c6c;
      border-color: #f56c6c;

      &:hover,
      &:focus {
        background-color: #f78989;
        border-color: #f78989;
      }
    }
  }
}
</style>